<!--
 * @Descripttion: 上传图片
 * @version:
 * @Author: lehaixia
 * @Date: 2022-10-25 15:57:01
 * @LastEditors: lehaixia
 * @LastEditTime: 2022-11-07 17:34:02
-->
<template>
  <div>
    <CFileInput v-if="!readonly" accept="image/*" :multiple="multiple" :show-album="showAlbum" class="upload-add" @success="successHandle" @error="errorHandle">
      <div v-if="imageList.length < limit"><van-icon name="plus" size="24" color="#B5B7C4" /></div>
    </CFileInput>
    <template>
      <FileItem v-for="(file,i) in fileList" :key="i" :index="i" :fit="fit" :item="file" :readonly="readonly" @click="clickPreviewHandle" @delete="handleDelete" />
    </template>
  </div>
</template>
<script>
import { uploadFile, deleteByAttachmentUseIds } from '@/apis/optyCategory'
import FileItem from '@/components/CFileInput/FileItem'
import CFileInput from '@/components/CFileInput'
import { ImagePreview } from 'vant'

export default {
  name: '',
  components: {
    FileItem,
    CFileInput
  },
  props: {
    imageList: { // 已上传的文件列表
      type: Array,
      default: () => []
    },
    maxSize: {
      type: Number,
      default: 1024 * 1024 * 20
    },
    multiple: {
      type: Boolean,
      default: true
    },
    parentIndex: {
      type: Number,
      default: 0
    },
    limit: {
      type: Number,
      default: 20
    },
    moduleType: {
      type: String,
      default: ''
    },
    objectId: {
      type: String,
      default: ''
    },
    fit: {
      type: String,
      default: 'contain'
    },
    showAlbum: {
      type: Boolean,
      default: true
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: this.imageList
    }
  },
  // 监听属性 类似于data概念
  computed: {

  },
  // 监控data中的数据变化
  watch: {
    imageList: {
      deep: true,
      immediate: true,
      handler() {
        this.fileList = this.imageList
      }
    }
  },
  created() {

  },
  // 方法集合
  methods: {
    // 删除图片
    async handleDelete(data) {
      if (data) {
        const newUrl = this.imageList.filter(v => v.attachmentPath !== data.attachmentPath)
        this.$set(this, 'fileList', newUrl)
        this.$emit('update', newUrl, this.parentIndex)

        if (data.useId) await deleteByAttachmentUseIds([data.useId]) // 删除远程图片
        this.$emit('delete', data)
      }
    },
    // 上传图片
    async  changeHandle(e) {
      let files = e.target.files
      files = [].slice.call(files)

      const maxCount = this.limit - this.imageList.length
      if (files.length > maxCount) {
        files = files.slice(0, maxCount)
      }

      const all = []
      for (const file of files) {
        var isImg = file.type.indexOf('image/') > -1
        if (!isImg) {
          const msg = `只能上传图片文件！`
          this.$toast.fail(msg)
          all.push(Promise.reject(msg))
          continue
        }
        // 验证文件大小
        const size = (file.size || 0)
        if (this.maxSize < size) {
          const msg = `上传图片大小不能超过${this.maxSize / 1024 / 1024}M!`
          this.$toast.fail(msg)
          all.push(Promise.reject(msg))
          continue
        }
        all.push(file)
      }
      const toast = this.$toast.loading({
        forbidClick: true,
        message: '图片上传中...',
        duration: 10000
      })

      const allPost = []
      await Promise.all(all).then(files => {
        files.forEach(file => {
          const p = new Promise((resolve, reject) => {
            const forms = new FormData()
            forms.append('file', file)
            forms.append('moduleType', this.moduleType)
            if (this.objectId) forms.append('objectId', this.objectId)

            uploadFile(forms).then(res => {
              const { success, data } = res
              if (success === 1 && data) {
                const newData = this.imageList.concat({ ...data })
                this.$emit('update', newData, this.parentIndex)
              }
              resolve(data)
            }).catch(e => {
              reject(e)
            })
          })
          allPost.push(p)
        })
      })
      Promise.all(allPost).then(res => {
        toast.clear()
      }).catch(e => {
        toast.clear()
        this.$toast.fail('网路请求超时')
        console.error(e)
      })
    },
    // 上传成功后触发
    successHandle(e) {
      this.changeHandle(e)
    },
    // 上传失败后触发
    errorHandle(err) {
      this.$toast.fail(err.toString())
    },
    // 查看图片
    clickPreviewHandle(i) {
      ImagePreview({
        images: this.fileList.map(e => this.$formatURL(e.attachmentPath)),
        startPosition: i || 0
      })
    }
  }
}
</script>
<style lang='less' scoped>
/* @import url(); 引入css类 */
.android-class {
  display: flex;
  flex-wrap: wrap;
}
.upload-add {
  width: 78px;
  height: 78px;

  border: 2px solid #EFF2F7;
  border-style: dotted;

  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 20px;
    height: 20px;
  }
}
</style>
